package com.yuan.aopbefore;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MyDynamicProxy {

    //目标对象
    private Object target;

    public MyDynamicProxy(Object target) {
        this.target = target;
    }

    public Object getProxy(){
        //代理对象
        Object proxy = null;
        //获取目标对象的类加载器
        ClassLoader classLoader = target.getClass().getClassLoader();
        //获取目标对象的接口
        Class<?>[] interfaces = target.getClass().getInterfaces();

        proxy = Proxy.newProxyInstance(classLoader, interfaces, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //获取方法名称
                String methodName = method.getName();
                //执行之前,日志功能
                MyLogging.methodBefore(methodName,args);
                //执行目标对象的方法
                Object rs = method.invoke(target, args);
                //执行之后,日志功能
                MyLogging.methodAfter(methodName,rs);
                return rs;
            }
        });

        return proxy;
    }



}